import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'drf2.settings'
import django
django.setup()
from aaa import models

x = models.Role.objects.filter(permissions__isnull=False).values('id', 'roleName', 'roleDesc', 'permissions__id',
                                                                 'permissions__authName',
                                                                 'permissions__url',
                                                                 'permissions__level',
                                                                 'permissions__pid').distinct()
print('x',x)
first_dict = {}
second_dict = {}
for item in x:
    role_id = item['id']
    level = item['permissions__level']
    id = item['permissions__id']
    pid = item['permissions__pid']
    node = {'id': item['permissions__id'], 'authName': item['permissions__authName'], 'url': item['permissions__url'],
            'level':level,
            'pid':pid}
    if role_id in first_dict:
        first_dict[role_id]['children'].append(node)
        #一级菜单没有pid
        if pid:
            if pid in second_dict:
                #if去重重复的二级菜单
                print(level, node)
                if node in second_dict[pid]['children']:
                    continue
                else:
                    #添加三级菜单
                    if level == 2:
                        continue
                    else:
                        second_dict[pid]['children'].append(node)

            else:
                second_dict[pid] = {'children':[node]}
    else:
        first_dict[role_id] = {'id':role_id,'roleName':item['roleName'],'roleDesc':item['roleDesc'],'children':[node]}

print(first_dict)
print(second_dict)

# for item1 in x:
#     # print(item)
#     level = item['permissions__level']
#     id = item['permissions__id']
#     pid = item['permissions__pid']
#     for item2 in first_dict.values():
#         for item3 in item2['children']:
#             if int(pid) == item3['id']:
#                 print(pid,item3['id'])
#                 print(item3)